/**
  * Created by Joshua Conero(O'Uymas) on 2016/12/6 0006.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  */
import java.io._

import scala.xml.XML
import conero.Helper

import scala.swing.TabbedPane

class Common extends Helper{
  val dir = System.getProperty("user.dir")
  val conf = dir+"/conf/crawler.xml"
  var reportLogDir = "/runtime/system.log"
  // app 属性
  override val author = "Joshua.Warner.Evan.Conero.Yang.Doeeking"
  override val version = "0.1.5"
  val createTime = "2016-11-28"
  configCheck()
  // 配置文件检测
  def configCheck():Unit = {
    // 文件存在性检测- 不存在则自动生成
    val fl = new File(conf)
    if(!fl.isFile){
      mkdir(fl.getParent)
      put_content(conf)
    }
    var application = ""
    try {
      application = (XML.load(conf) \ "application").toString()
    }
    //XML.save(conf,"cawler","utf-8")
    //val root = config\"crawler"\"application"
    if(application == "") {
      val date = sysdate()
      val root =
        <config>
          <application>
            <author>Conero Joshua</author>
            <date>
              {date}
            </date>
          </application>
        </config>
      XML.save(conf, root, "utf-8", true, null)
    }
    // 运行记录
    val app = XML.load(conf)\"application"
    val runtime = app\"runtime"
    var runtimeDir = if((runtime\"@dir").toString == "") "/runtime" else (runtime\"@dir").toString
    mkdir(dir+runtimeDir)
    reportLogDir = if((runtime\"@logFile").toString == "") reportLogDir else (runtime\"@logFile").toString
    reportLogDir = dir+reportLogDir
  }
  // 日志登记函数
  def reportLog(content:String,suffix:Boolean = true):Unit = {
    val report = if(suffix == true) "("+sysdate()+")******************\r\n"+content+"\r\n" else content
    file_append(reportLogDir,report)
  }
  // 编译次数
  def complierCount(vtype:String = ""):Int = {
    val retArr = getComplier()
    var ctt = retArr(0)
    var count = str2int(ctt)
    if(vtype == "create"){
      count = count + 1
      getComplier(count.toString+"="+sysdate())
    }
    count
  }
  // 读取编译日志信息
  def getComplier(content:String = ""):Array[String] = {
    val complierFile = dir+"/conf/complier."+version+".conero"
    if(content != ""){
      put_content(complierFile,base64_encode(content))
      return Array("0",sysdate())
    }
    var ctt = get_content(complierFile)
    if(ctt != "") ctt = base64_decode(ctt)
    else ctt = "0="+sysdate()
    ctt.split("=")
  }
  // 获取crawler.xml 文件对象
  def getXml() = XML.load(conf)
  // 获取crawler.xml 文件对象的 application 节点
  def getAppConf() = getXml()\"application"

}
/*
// 验证 tab是否已经存在，防止重复生中
def tabExist(tab:TabbedPane,title:String):Boolean = {
  val all = tab.selection.index
  if( all >= 0){
    for(i <- 0 to all){
      tab.selection.page(i) ??
    }
  }
  false
}
*/


